import { Token, Message, Tcallback, FileItem } from "./report"

interface CallbackManager {
    [uuid: number]: Tcallback
}



class DhsReport {
    private serverUUID: number;
    private _uuid: number;
    private callbackManager: CallbackManager;
    private server: WebSocket;

    constructor() {

        this.callbackManager = {};
        this._uuid = 0;
        this.serverUUID = new Date().getTime();
        this.server = null;
        this.checkServer()

    }
    private checkServer() {
        setInterval(() => {
            this.getWsServer()
        }, 1000);
    }
    private getWsServer(): Promise<WebSocket> {
        const _this = this;
        return new Promise((resolve) => {
            if (this.server && (this.server.CONNECTING == this.server.readyState || this.server.OPEN === this.server.readyState)) {

                resolve(this.server);
            } else {

                this.server = new window.WebSocket("ws://127.0.0.1:60706/dhs");
                this.initServer();
                // this.server.send(JSON.stringify({ [Token.uuid_token]: this.serverUUID }))
                console.log("server===init======", this.server);
                resolve(this.server);
                this.server.send(JSON.stringify({
                    [Token.data_type]: Token.type_connect,
                    [Token.command_token]: Token.c_dhs_exportpdf,
                    [Token.uuid_token]: -1,
                    [Token.server_uuid_token]: _this.serverUUID
                }));
            }
        })

    }



    private getUUID(): number {
        this._uuid = new Date().getTime();
        return this._uuid;
    }

    private initServer() {

        const _this = this;
        this.server.onerror = function () {
            console.log("onerror===========");
        };

        this.server.onmessage = function (e) {

            const msg = JSON.parse(e.data);
            const uuid = msg[Token.uuid_token];

            switch (msg[Token.data_type]) {
                case Token.type_command_end:
                    console.log("onmessage===========", msg[Token.data_token]);

                    break;
                case Token.type_error:
                    console.log("onmessage===========", msg[Token.data_token]);
                    break;
                case Token.type_save_call:
                    console.log("type_save_call========  ");
                    const _sendMsg = (save_status: number) => {

                        const resultMsg: Message = {
                            [Token.data_type]: Token.type_return_status,
                            [Token.uuid_token]: msg[Token.uuid_token],
                            [Token.data_token]: save_status,
                            [Token.server_uuid_token]: _this.serverUUID
                        };

                        _this.getWsServer().then((ws: WebSocket) => {

                            ws.send(JSON.stringify(resultMsg));
                            console.log("type_save_call send  ");
                        }).catch(() => {
                            _sendMsg(0)
                        });
                    }
                    if (_this.callbackManager.hasOwnProperty(uuid)) {
                        const fun = _this.callbackManager[uuid];
                        fun(msg[Token.data_token], {
                            success: () => {
                                _sendMsg(1)
                            }, fail: () => {
                                _sendMsg(0)

                            }
                        })

                    } else {
                        _sendMsg(0)
                    }

                    break;

                default:
                    break;


            }


        };
        this.server.onclose = function () {
        };

    }


    private sendMessage(msg: Message) {
        this.getWsServer().then((ws: WebSocket) => {
            if (Object.hasOwnProperty.call(msg, Token.jsonDbData_token)) {
                msg[Token.jsonDbData_token] = JSON.stringify(msg[Token.jsonDbData_token]);
            }
            ws.send(JSON.stringify(msg));
        });
    }

    dhs_imagepath(callback: Tcallback) {

        const _this = this;
        const msg: Message = {
            [Token.data_type]: Token.command_token,
            [Token.command_token]: Token.c_dhs_image_dir,
            [Token.uuid_token]: _this.getUUID(),
            [Token.server_uuid_token]: _this.serverUUID
        };
        if (callback) {
            this.callbackManager[msg[Token.uuid_token]] = callback;
            this.sendMessage(msg);
        }

    }
    dhs_exportpdf(jsonDbData: Object, tpl: string, callback: Tcallback, urlList?: FileItem[]) {
        const _this = this;
        const msg: Message = {
            [Token.data_type]: Token.command_token,
            [Token.command_token]: Token.c_dhs_exportpdf,
            [Token.jsonDbData_token]: jsonDbData,
            [Token.template_token]: tpl,
            [Token.uuid_token]: _this.getUUID(),
            [Token.server_uuid_token]: _this.serverUUID,
            [Token.urlList_token]: urlList
        };

        if (callback) {
            this.callbackManager[msg[Token.uuid_token]] = callback;
            this.sendMessage(msg);
        }
    }

    dhs_design(jsonDbData: Object, tpl: string, callback: Tcallback, urlList?: FileItem[]) {
        const _this = this;
        const msg: Message = {
            [Token.uuid_token]: _this.getUUID(),
            [Token.server_uuid_token]: _this.serverUUID,
            [Token.data_type]: Token.command_token,
            [Token.command_token]: Token.c_dhs_design,
            [Token.jsonDbData_token]: jsonDbData,
            [Token.template_token]: tpl,
            [Token.urlList_token]: urlList
        };

        if (callback) {
            this.callbackManager[msg[Token.uuid_token]] = callback;
            this.sendMessage(msg);

        }
    }

    dhs_show(jsonDbData: Object, tpl: string, urlList?: FileItem[]) {

        const _this = this;
        const msg: Message = {
            [Token.uuid_token]: _this.getUUID(),
            [Token.server_uuid_token]: _this.serverUUID,
            [Token.data_type]: Token.command_token,
            [Token.command_token]: Token.c_dhs_show,
            [Token.jsonDbData_token]: jsonDbData,
            [Token.template_token]: tpl,
            [Token.urlList_token]: urlList
        };

        this.sendMessage(msg);
    }
    dhs_print(jsonDbData: Object, tpl: string, copys: number = 1, urlList?: FileItem[]) {

        const _this = this;
        const msg: Message = {
            [Token.uuid_token]: _this.getUUID(),
            [Token.server_uuid_token]: _this.serverUUID,
            [Token.data_type]: Token.command_token,
            [Token.command_token]: Token.c_dhs_print,
            [Token.jsonDbData_token]: jsonDbData,
            [Token.template_token]: tpl,
            [Token.urlList_token]: urlList,
            [Token.copys_token]: copys

        };
        this.sendMessage(msg);
    }


}


const dhsReport = new DhsReport()

export default dhsReport;